import { AfterViewInit, Component, ViewChild } from '@angular/core';
import { IonTabs } from '@ionic/angular';
import { HttpService } from '../service/http.service';
import { MessageService } from '../service/message.service';

@Component({
  selector: 'app-tabs',
  templateUrl: 'tabs.page.html',
  styleUrls: ['tabs.page.scss']
})
export class TabsPage implements AfterViewInit {

  @ViewChild('tabs')
  tabsRef: IonTabs;

  items = [
    { name: 'chats', text: '微信', icon: 'chatbubble-outline', count: 100, nohup: false },
    { name: 'address-book', text: '通讯录', icon: 'people-outline', nohup: true },
    { name: 'discovery', text: '发现', icon: 'compass-outline', count: 0, nohup: false },
    { name: 'me', text: '我', icon: 'person-outline', nohup: true }
  ]

  constructor(private messageService: MessageService, private httpService: HttpService) {
    this.messageService.getMessageCount().subscribe(count => this.items[0].count = count)
  }

  ngAfterViewInit() { }

  onSwipe(event) {
    if (event.deltaX > 40) { // 向右滑动
      for (let index = 0; index < this.items.length; index++) {
        if (this.tabsRef.getSelected() == this.items[index].name) {
          if (index + 1 < this.items.length) {
            this.tabsRef.select(this.items[index + 1].name)
          }
          break;
        }
      }
    } else if (event.deltaX < -40) { // 向左滑动
      for (let index = 0; index < this.items.length; index++) {
        if (this.tabsRef.getSelected() == this.items[index].name) {
          if (index - 1 >= 0) {
            this.tabsRef.select(this.items[index - 1].name)
          }
          break;
        }
      }
    }
  }

  tabAfterChange() {
    for (let index = 0; index < this.items.length; index++) {
      if (this.tabsRef.getSelected() == this.items[index].name) {
        if (this.items[index].icon.endsWith('-outline')) {
          this.items[index].icon = this.items[index].icon.substring(0, this.items[index].icon.lastIndexOf('-outline'))
        }
      } else {
        if (!this.items[index].icon.endsWith('-outline')) {
          this.items[index].icon = this.items[index].icon + '-outline'
        }
      }
    }
  }
}
